﻿using Infrastructure.Model;
using Microsoft.AspNetCore.Http;
using System.Net.Http.Headers;
using System.Text;
using UAParser;

namespace Infrastructure.Http
{
    public class HttpHelper
    {
        /// <summary>
        /// 发起 HTTP POST 请求
        /// </summary>
        /// <param name="url">请求的 URL</param>
        /// <param name="postData">POST 数据</param>
        /// <param name="contentType">Content-Type，默认为 application/json</param>
        /// <param name="timeOut">超时时间（秒），默认为 30 秒</param>
        /// <param name="headers">请求头</param>
        /// <returns>响应内容</returns>
        public static string HttpPost(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            postData = postData ?? "";
            using HttpClient httpClient = new HttpClient();
            if (headers != null)
            {
                foreach (KeyValuePair<string, string> header in headers)
                {
                    httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
            }

            using HttpContent httpContent = new StringContent(postData, Encoding.UTF8);
            if (contentType != null)
            {
                httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            }

            HttpResponseMessage result = httpClient.PostAsync(url, httpContent).Result;
            return result.Content.ReadAsStringAsync().Result;
        }

        /// <summary>
        /// 异步发起 HTTP POST 请求
        /// </summary>
        /// <param name="url">请求的 URL</param>
        /// <param name="postData">POST 数据</param>
        /// <param name="contentType">Content-Type</param>
        /// <param name="timeOut">超时时间（秒）</param>
        /// <param name="headers">请求头</param>
        /// <returns>响应内容</returns>
        public static async Task<string> HttpPostAsync(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
        {
            postData = postData ?? "";
            using HttpClient client = new HttpClient();
            client.Timeout = new TimeSpan(0, 0, timeOut);
            if (headers != null)
            {
                foreach (KeyValuePair<string, string> header in headers)
                {
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
            }

            using HttpContent httpContent = new StringContent(postData, Encoding.UTF8);
            if (contentType != null)
            {
                httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            }

            return await (await client.PostAsync(url, httpContent)).Content.ReadAsStringAsync();
        }

        /// <summary>
        /// 发起 HTTP GET 请求
        /// </summary>
        /// <param name="url">请求的 URL</param>
        /// <param name="headers">请求头</param>
        /// <returns>响应内容</returns>
        public static string HttpGet(string url, Dictionary<string, string> headers = null)
        {
            using HttpClient httpClient = new HttpClient();
            if (headers != null)
            {
                foreach (KeyValuePair<string, string> header in headers)
                {
                    httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
            }
            else
            {
                httpClient.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded");
                httpClient.DefaultRequestHeaders.Add("UserAgent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            }

            try
            {
                HttpResponseMessage result = httpClient.GetAsync(url).Result;
                return result.Content.ReadAsStringAsync().Result;
            }
            catch (Exception ex)
            {
                Console.WriteLine("[Http请求出错]" + url + "|" + ex.Message);
            }

            return "";
        }

        /// <summary>
        /// 异步发起 HTTP GET 请求
        /// </summary>
        /// <param name="url">请求的 URL</param>
        /// <param name="headers">请求头</param>
        /// <returns>响应内容</returns>
        public static async Task<string> HttpGetAsync(string url, Dictionary<string, string> headers = null)
        {
            using HttpClient client = new HttpClient();
            if (headers != null)
            {
                foreach (KeyValuePair<string, string> header in headers)
                {
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
            }

            return await (await client.GetAsync(url)).Content.ReadAsStringAsync();
        }

        /// <summary>
        /// 记录用户登录信息
        /// </summary>
        /// <param name="context">获取客户端信息和用户相关信息</param>
        /// <param name="status">登录状态</param>
        /// <param name="message">登录相关的消息</param>
        /// <returns></returns>
        public static SysLogininfo RecordLogInfo(HttpContext context, string status, string message)
        {
            // 获取客户端IP地址
            string clientIp = context.Connection.RemoteIpAddress?.ToString();
            // 获取客户端信息
            string browser = context.Request.Headers["User-Agent"].ToString();
            var uaParser = Parser.GetDefault(); // 使用 UAParser.NET 的示例
            ClientInfo clientInfo = uaParser.Parse(browser);
            string os = clientInfo.OS.Family; // 获取操作系统信息

            return new SysLogininfo
            {
                Browser = browser,
                OS = os,
                Ipaddr = clientIp,
                Msg = message,
                UserName = context.User.Identity?.Name,
                Status = status,
                LoginLocation = ""
            };
        }
    }
}
